package com.unitd.frame.comm.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @desc 关于异常的工具类
 * @filename ExceptionUtils.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2016/10/21
 */
public class ExceptionUtils extends org.apache.commons.lang3.exception.ExceptionUtils {

	/**
	 * @desc 将CheckedException转换为UncheckedException.
	 * @param e 异常对象
	 * @return RuntimeException
	 */
	public static RuntimeException unchecked(Exception e) {
		if (e instanceof RuntimeException) {
			return (RuntimeException) e;
		} else {
			return new RuntimeException(e);
		}
	}

	/**
	 * @desc 将异常消息转换为UncheckedException.
	 * @param errMsg 异常消息
	 * @return RuntimeException
	 */
	public static RuntimeException unchecked(String errMsg) {
		return new RuntimeException(errMsg);
	}

	/**
	 * @desc 将ErrorStack转化为String.
	 * @param e 异常对象
	 * @return String
	 */
	public static String getStackTraceAsString(Throwable e) {
		if (e == null) {
			return "";
		}
		StringWriter stringWriter = new StringWriter();
		e.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}

	/**
	 * @desc 判断异常是否由某些底层的异常引起.
	 * @param ex                    异常对象
	 * @param causeExceptionClasses 异常类型
	 * @return boolean
	 */
	public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
		Throwable cause = ex.getCause();
		while (cause != null) {
			for (Class<? extends Exception> causeClass : causeExceptionClasses) {
				if (causeClass.isInstance(cause)) {
					return true;
				}
			}
			cause = cause.getCause();
		}
		return false;
	}

	/**
	 * @desc 在request中获取异常类
	 * @param request rquest请求
	 * @return Throwable
	 */
	public static Throwable getThrowable(HttpServletRequest request) {
		Throwable ex = null;
		if (request.getAttribute("exception") != null) {
			ex = (Throwable) request.getAttribute("exception");
		} else if (request.getAttribute("javax.servlet.error.exception") != null) {
			ex = (Throwable) request.getAttribute("javax.servlet.error.exception");
		}
		return ex;
	}
}